package com.rpc.protocol;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import static com.dyuproject.protostuff.runtime.RuntimeSchema.getSchema;

/**
 * @author yanzhuoleo
 * @version V1.0
 * @Description:
 * @date 2018-01-16-下午6:32
 */
public class ProtostuffSerializeImpl implements ISerialize {

    private static Objenesis objenesis = new ObjenesisStd(true);

    @Override
    public <T> byte[] serialize(T transportData) {
        Class<T>     cls    = (Class<T>) transportData.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(transportData, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> objectClass) {
        try {
            T message = objenesis.newInstance(objectClass);
            Schema<T> schema = getSchema(objectClass);
            ProtostuffIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    public static void main(String[] args) {

    }

}
